<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c"%>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="renderer" content="webkit">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>项目信息</title>
<jsp:include page="../../import.jsp" flush="true" />
 <script type="text/javascript" src="<%=path %>/resource/lib/plugins/ajaxfileupload.js"></script>
</head>
<body class="iframeBody">
 <div class="Wrapper">
        <div>
           <div id="pageInTab" class="pageInTab">
		   <div tabid="tabA" title="基本信息" lselected="true">
		<form id="fnc_prj_bsc_info_form"  enctype = “multipart/form-data” >
             <div class="fieldset1 tabel_col clearFix">
              <div class="fieldBox col_100">
                    <div class="label">项目名称</div>
                <div class="field">
                     <span id="fncprjnm" name="fncprjnm">&nbsp;${fncPrjBscInfo.fncprjnm}</span>
                </div>
                <div style="display: none">
                </div>
             </div>
             <div class="fieldBox col_50">
                <div class="label">金融机构</div>
                <div class="field">
                    <span id="fncinsNM" name="fncinsNM">&nbsp;${fncPrjBscInfo.fncinsNM}</span>
                </div>
                <div style="display: none">
                </div>
             </div>
                             <div class="fieldBox col_50">
                    <div class="label">金融机构类型</div>
                    <div class="field">
                    <span id="instypeNM" name="instypeNM">&nbsp;${fncPrjBscInfo.instypeNM}</span> 
                </div>
                <div style="display: none">
                </div>
             </div>
             <div class="fieldBox col_100">
                    <div class="label">融资报价</div>
                <div class="field">
                 	<span name="fncScmNm" id="fncScmNm" onclick="showScmDetail()" style="color:blue;text-decoration:underline">&nbsp;${fncPrjBscInfo.fncscmNM}</span>
                </div>
                <div style="display: none">
                </div>
             </div>
           <div class="fieldBox col_50">
                    <div class="label">国家</div>
                <div class="field">
                  <span id="countryNM" name="countryNM">&nbsp;${fncPrjBscInfo.countryNM}</span>
                </div>
                <div style="display: none">
                </div>
             </div>
                
		 <div class="fieldBox col_50">
                <div class="label">业务类型</div>
                <div class="field">
                   <span id="bustypeNM" name="bustypeNM">&nbsp;${fncPrjBscInfo.bustypeNM}</span>
                </div>
                <div style="display: none">
                </div>
              </div>
          <div class="fieldBox col_50">
                    <div class="label">项目金额</div>
                <div class="field">
                    <span id="fncprjamt" name="fncprjamt">&nbsp;${fncPrjBscInfo.fncprjamt/100}</span>
                </div>
                <div style="display: none">
                </div>
             </div>   
              <div class="fieldBox col_50">
                    <div class="label">融资金额</div>
                <div class="field">
                    <span id="fncprjamt" name="fncprjamt">&nbsp;${fncPrjBscInfo.fncfiamt/100}</span>
                </div>
                <div style="display: none">
                </div>
             </div>  
               <div class="fieldBox col_50">
                    <div class="label">方案XIRR(%)</div>
                <div class="field">
                    <span id="irr" name="irr">&nbsp;${fncPrjBscInfo.irr*100}</span>
                </div>
                <div style="display: none">
                </div>
             </div>              
                 
              <div class="fieldBox col_50">
                    <div class="label">实际融资金额</div>
                <div class="field">
                    <input name="acFiAmt" id="acFiAmt" type="text" readonly="readonly" class="ui-textbox" value="${fncPrjBscInfo.acFiAmt/100.00}" onchange="changeAmt(this.value)" validate="{number:true,required:true}" >
                </div>
                <div style="display: none">
                </div>
             </div>          
              <div class="fieldBox col_50">
                    <div class="label">实际XIRR(%)</div>
                <div class="field">
                    <input name="acXirr" id="acXirr"   type="text" class="ui-textbox" value="${fncPrjBscInfo.acXirr*100}" validate="{number:true,required:true}" >
                    <span id="xirrBtn" class="sq-button sq-button-round" onclick="getRixx()"> <i class="sqBtnIco_10"></i> 计算</span>
                </div>
                <div style="display: none">
                </div>
             </div> 
              <div class="fieldBox col_50">
                    <div class="label">久期值:</div>
                <div class="field">
                    <input name="dura" id="dura"   type="text" class="ui-textbox" value="${fncPrjBscInfo.dura}" validate="{number:true,required:true}" >
                 <span id="duraBtn" class="sq-button sq-button-round" onclick="getdura()"><!-- <i class="sqBtnIco_10"></i> -->计算</span>
                </div>
                <div style="display: none">
                </div>
             </div>     
                 <div class="fieldBox col_50">
                    <div class="label">首付款金额</div>
                <div class="field">
               <input name="fstpyamtall" id="fstpyamtall" readonly="readonly" type="text" class="ui-textbox" value="${fncPrjBscInfo.fstpyamtall/100.00}" readonly="readonly" validate="{number:true,required:true}" >
               <input name="fstpyamt" id="fstpyamt" type="hidden" class="ui-textbox" value="${fncPrjBscInfo.fstpyamt/100.00}">
                </div>
                <div style="display: none">
                </div>
             </div> 
              <div class="fieldBox col_50">
                    <div class="label">首付款是否坐扣</div>
                <div class="field">
                    <input name="wthrddctNM" id="wthrddctNM" readonly="readonly" type="text" class="ui-textbox" value="${fncPrjBscInfo.wthrddct}" readonly="readonly">
                </div>
                <div style="display: none">
                </div>
             </div>
             
             <div class="fieldBox col_50">
                    <div class="label">融资期数</div>
                <div class="field">
                    <input name="payplanpd" id="payplanpd" readonly="readonly" type="text" class="ui-textbox" value="${fncPrjBscInfo.payplanpd}" validate="{number:true,required:true}" >
                </div>
                <div style="display: none">
                </div>
             </div>          
             

             
              <div class="fieldBox col_50">
                    <div class="label">融资行数</div>
                <div class="field">
                    <input name="payplanli" id="payplanli" readonly="readonly"  type="text" class="ui-textbox" value="${fncPrjBscInfo.payplanli}"  validate="{number:true,required:true}" >
                <input name="prjid" id="prjid" type="hidden" class="ui-textbox" value="${id}">
                   <input name="maxli" id="maxli" type="hidden" class="ui-textbox" value="0">
                   <input name="maxpd" id="maxpd" type="hidden" class="ui-textbox" value="0">
                   <input name="flsum" id="flsum" type="hidden" class="ui-textbox" value="0">
                   <input name="paysum" id="paysum" type="hidden" class="ui-textbox" value="0">
                </div>
                <div style="display: none">
                </div>
             </div> 
             
             
             
             
             
             
             
             
             <div class="fieldBox col_50">
                    <div class="label">实际到账日期</div>
                <div class="field">
                    <span id="transtm" name="transtm">&nbsp;${fncPrjBscInfo.transtm}</span>                  
                </div>
                <div style="display: none">
                </div>
             </div>       
                <div class="fieldBox col_50">
                    <div class="label">实际到账金额</div>
                <div class="field">
                <span id="transam" name="transam">&nbsp;${fncPrjBscInfo.transam/100.00}</span>  
                </div>
                <div style="display: none">
                </div>
             </div> 
             
               <div class="fieldBox col_50">
                    <div class="label">收款银行</div>
                <div class="field">
                 <span id="transbank" name="transbank">&nbsp;${fncPrjBscInfo.transbank}</span>  
                   
                </div>
                <div style="display: none">
                </div>
             </div>      
             
               <div class="fieldBox col_50">
                    <div class="label">收款账号</div>
                <div class="field">
                 <span id="transacc" name="transacc">&nbsp;${fncPrjBscInfo.transaccNm}</span>  
                </div>
                <div style="display: none">
                </div>
             </div> 
              <div class="fieldBox col_50">
                    <div class="label">实际利率(%)</div>
                <div class="field">
                    <c:if test="${not empty fncPrjBscInfo.scmIntrtReal}">
					    <input name="scmIntrtReal" id="scmIntrtReal"   type="text" class="ui-textbox" value="${fncPrjBscInfo.scmIntrtReal*100}" validate="{number:true}" >
					</c:if>
					<c:if test="${empty fncPrjBscInfo.scmIntrtReal}">
					    <input name="scmIntrtReal" id="scmIntrtReal"   type="text" class="ui-textbox" value="${fncPrjBscInfo.scmIntrt*100}" validate="{number:true}" >
					</c:if>
                </div>
             </div>
             <div class="fieldBox col_50">
                    <div class="label">还本方式</div>
                <div class="field">
                    <select id="repayType" name="repayType" ligerui="width:180" validate="{required:true}">
						<c:forEach items="${repayTypeList}" var="item">
							<option value="${item.key}"
								<c:if test="${item.key ==fncPrjBscInfo.repayType}">selected="selected"</c:if>>${item.value}</option>
						</c:forEach>
					</select> 
                </div>
             </div> 
                          
            </div>
               <div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">融资端费用信息 </span>
					</div>
					<div class="fieldBox col_100">
							<div id="cost0" class="sq-grid">
							</div>
					</div>
            </div> 
              <div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">还款表信息 </span>
						
					</div>
					<div class="fieldBox col_100">
			
						<div style="margin-left: auto;margin-right: 10px;width:700px;">
							<span id="scm_cost2_EXCEL_INPORT" >
							   <a id="upmodel" style="color:blue;text-decoration:underline;" href="<%=path %>/resource/template/reffile/payplandemo.xls" />模板样例下载</a>&nbsp;&nbsp;&nbsp;&nbsp;
							</span>
							<span id="scm_cost2_EXCEL_INPORT" >
							   <input type="file" id="upfile" name="upfile" /><span class="sq-button sq-button-round" onclick="ReadExcel();" >导入</span>
							</span>
							<span id="scm_cost2_add_btn_id"
								class="sq-button sq-button-round" >新增
							</span>
							<span id="scm_cost2_del_btn_id"
								class="sq-button sq-button-round"  >删除选中行
							</span>
						</div>
					</div>
					<div class="fieldBox col_100">
							<div id="cost1" class="sq-grid">
							</div>
					</div>
            </div>
  			 <div class="btnsBox">
               <span id="saveBtn" class="sq-button sq-button-round" onclick="save()"><!-- <i class="sqBtnIco_10"></i> -->提交</span>
               <span id="cancelBtn" class="sq-button sq-button-round" onclick="cancelBtn()"><!-- <i class="sqBtnIco_14"></i> -->取消</span>
         <%--    <jsp:include page="../../system/sysUlFilesRec/sysUlFileRecList.jsp" flush="true" >
				                <jsp:param name="pkId" value="${id }"/>
				                <jsp:param name="tabNm" value="FNC_PRJ_PAY_PLAN"/>
			</jsp:include> --%>
				<!-- 附件显示 -->
					<div class="fieldBox col_100">
						<div style="width: 98%; margin-left: 1%;">
							<jsp:include page="../frCommFilesList.jsp" flush="true" ></jsp:include>
							<div id="ligergrid_file1" class="sq-grid"></div>
						</div>
					</div>
				
            </div>
            <!-- hide data -->
         
        </form>
        </div>
              
        </div>
        </div>
    </div>
    
	<script type="text/javascript">
	  var pageInApp={
	    		flag:true
	    };
	  var griddata1;
	  var griddata0;
	  var id ='${id}';
	  var selectOrgCd = "";
	   var searchOrgTree = null;
	  var firstNode = null;
	  var textName='${orgTextName}';//节点名称
	  var orgData = null;
		var id ="";//初始值
		var detailFlag = '${detailFlag}';
		var isFlow = '${isFlow}';
		var editFlag='${editFlag}';
$(function () {
	initData();
	loadFilesLiger('hkb',1, $("#prjid").val(),'no');//加载还款表附件信息
	
});
	//初始化数据
	function initData(){
		//	initOrgTree();
    $("#fncprjamt").val(new  Number("${fncPrjBscInfo.fncprjamt/100}"));
    $("#transam").val(new  Number("${fncPrjBscInfo.transam/100}"));
    $("#acFiAmt").val(new  Number("${fncPrjBscInfo.acFiAmt/100}"));
    $("#fstpyamt").val(new  Number("${fncPrjBscInfo.fstpyamt/100}"));
    $("#fstpyamtall").val(new  Number("${fncPrjBscInfo.fstpyamtall/100}"));
    $("#transam").html(new  Number("${fncPrjBscInfo.transam/100}"));
			f_initCostData1();
			f_initCostData0();
		 initTab();
		 
		 if($("#wthrddctNM").val()==1){
			 $("#wthrddctNM").val("坐扣");
		 }else{
			 $("#wthrddctNM").val("不坐扣");
		 }
			$("#fnc_prj_bsc_info_form").ligerForm({
			    validate: true
			});
			 var ligerForm = liger.get("fnc_prj_bsc_info_form");
		 $("#fnc_prj_bsc_info_form").check_ligerFormEditor();
		
		/*  // 设置业务种类默认为禁用
		    var slt=liger.get("loanTypCd");
            slt.setDisabled();
 */
	
		
		 $(function() {
				
				var transtm = "${fncPrjBscInfo.transtm}";
				//alert(transtm);
				if(null != transtm&&transtm!=''){
					var date = new Date(transtm);
				//	alert(date);
					$("#transtm").text(DateUtils.formatDate(date, DateUtils.YYYY_MM_DD));
				}
			
			});
	

	}
	var pageInTab = null;
	  var loadedTabs=[]

	
	  

	  
   
	
	//初始化Tab
    function initTab(){
    	 pageInTab = $("#pageInTab").ligerTab({
             height: 'auto',
             contextmenu: false,
             minIframeHeight: GET_minIframeHeight(),
             onBeforeSelectTabItem: function (tabid) {
             	var id = $("#prjid").val();
             		//alert("id="+id);
             	 if(tabid!="tabA"){
 	             	if(id==null||id==''){
 	                	top.$.ligerDialog.SQalert({content:"请先保存项目基本信息", SQ_type: "warning"});
 	                	return false;
 	                } 
             	} 
             },
             onAfterSelectTabItem: function(tabid) {
              //   if (loadedTabs.indexOf(tabid)<0) {
                 	var id = $("#prjid").val();
                 	//alert("id="+id);
                 	 if(tabid!="tabA"){
 	                	if(id==null||id==''){
 	                		 top.$.ligerDialog.SQalert({content: LogUtils.LOG_PRJ__PRD_SELECT_BEFORE, SQ_type: "warning"});
 	                         return false; //验证不通过，不执行以下代码
 	                	}
                 	} 
                     loadedTabs.push(tabid);
                   //  switch (tabid){
                   //      case "tabB":
                           //  pageInTab.setTabItemSrc(tabid, "<%=path%>/rfbuss/fncprjbscinfo/toSysscoreIdxListPage.do?id="+id+"&&detailFlag="+detailFlag);
                   //          break;
                        
                             
                   //  }
            //     };
                 SetIframe_height();
             }
         });

         $.extend(true, pageInApp, {
             pageInTab: pageInTab
         });
    };
	//保存项目基础信息
	function save(){
	//	alert(JSON.stringify( griddata0.getData()))
		var ligerForm = liger.get("fnc_prj_bsc_info_form");
        if (!ligerForm.valid()) {
            top.$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO,SQ_type: "warning"});
            return false; //验证不通过，不执行以下代码
        }
        //=======================================校验begin====================================
        var paysum=new Number($("#paysum").val());
        var flsum=new Number($("#flsum").val());
        var acFiAmt=new Number("${fncPrjBscInfo.acFiAmt/100.00}");
        var transam=new Number("${fncPrjBscInfo.transam/100.00}");
        var wthrddctNM=$("#wthrddctNM").val();
        var fstpyamt=new Number($("#fstpyamt").val());
        var acXirr=new Number($("#acXirr").val());       
        if(acFiAmt<=0){
        	top.$.ligerDialog.SQalert({content:"实际融资金额必须大于0",SQ_type: "warning"});
            return false; 
        }
        if(transam<0){
        	top.$.ligerDialog.SQalert({content:"实际到账金额必须大于0",SQ_type: "warning"});
            return false; 
        }
      //  alert(transam-(paysum+flsum));
      //  if(wthrddctNM=="坐扣"){
        	//alert(transam);
        	//alert(paysum);
        	//alert(acFiAmt);
        	//alert(paysum-acFiAmt);
        	//alert(flsum);
        	//alert(transam-(paysum+flsum));
        	//if(acFiAmt!=(paysum+flsum)){
          //      top.$.ligerDialog.SQalert({content:"融资端金额与还款明细金额总和必须 等于："+acFiAmt,SQ_type: "warning"});
          //      return false; 	
        //	}
      //  }else{
         	if(acFiAmt.toFixed(2)-paysum.toFixed(2)!=0){
                top.$.ligerDialog.SQalert({content:"还款明细金额总和必须 等于："+(acFiAmt),SQ_type: "warning"});
                return false; 	
        	}
     //   }
//          2018-04-28费用项为保证金时，计划退回时间为必填
    		var yz1 = getSelectRow();
    		 //还款表增加预计退回时间校验劣后费用(超额抵押)不为0，预计退回时间不为空
            var yz2 = getSelectRowcost1();
    		var ckrzd=validateGrid();
//             alert("validateGrid()="+validateGrid()+"***ckrzd="+ckrzd);
            if(!ckrzd){
            	   return false; 	
            }
           
       
     //   return false; 	
        //====================================校验 end===============================================
        	//判断校验是否执行完
 				if(ckrzd && yz2 && yz1){
	    				  var data = ligerForm.getData();
	    			       data["id"]=$("#prjid").val();
	    			       if(data["orgCd"]==""){
	    			       data["orgCd"]='${orgCd}';
	    			       }
	    			       var payplanlist = griddata1.getData();
	    			       var fllist = griddata0.getData();
	    			       data["payplanlist"] = JSON.stringify(payplanlist);
	    			       data["fllist"] = JSON.stringify(fllist);
	    			        var url = '<%=path%>/rfbuss/fncprjbscinfo/payplanadd.do';

	    			        var wait_dialog;
	    			        $.ajax({
	    			    		type: 'post',
	    			    		dataType:'json',
	    			    		data:data,
	    			    		url: url,
	    			    		beforeSend: function(){
	    					          wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
	    					     },
	    			    		success:function(msg){
	    			    			 wait_dialog.close();
	    			    			 if(msg.success == 1){
	    			    			 	top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "success"})
	    			    				 var chflag="${chflag}";
	    			    				 if(chflag=="1"){
	    			    				//	 flowStart();	 
	    			    				 }
	    			    				 
	    			    				//	 top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "success"});
	    						          	 	$("#prjid").val(msg.data);
	    						          	 	pageInApp.flag=false;
	    						          	 	ajaxFileUploadImg();
	    			    			 }else{
	    			    				 top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
	    			    			 }
	    			    		}
	    			    	});
 				}
     	    	
	}
	//取消
	function cancelBtn(){
		  var TAB=top.mainApp.parentTab;
          var currentTabid=TAB.getSelectedTabItemID();
          if(top.tab.isTabItemExist("${currentTabid}")){
	        	  top.tab.reload("${currentTabid}");  
	          }
		 top.tab.removeTabItem(currentTabid);

	}
	  function f_initCostData1()
	    { 
			if(editFlag==''){
				editFlag=true;
			}
			var id=$("#prjid").val();
			var url='<%=path%>/rfbuss/fncprjbscinfo/initpayplanList.do?id='+id;
	    	griddata1 = $("#cost1").ligerGrid({
	    		url:url,
	            method: 'get',
	                columns: [
	                	
		                { display: '行数', width: 100, name: 'lineNum',editor: { type: 'text' },
		                	render:function(item, rowindex){
		                		item.lineNum=rowindex+1;
		                		return item.lineNum;
		                	},
		                	 totalSummary:
			                    {
			                        render: function (suminf, column, cell)
			                        {
			                        	//alert(suminf.count+":"+suminf.sum);
			                        	$("#maxli").val(suminf.count);
			                        	
			                     
			                            return '<div>总共:' + suminf.count + '</div>';
			                        },
			                        align: 'left'
			                    }
		              
		                },
		                { display: '期数', width: 100, name: 'pdMun',editor: { type: 'text' },
		                	totalSummary:
		                    {
		                        render: function (suminf, column, cell)
		                        {
		                        	//alert(suminf.count+":"+suminf.sum);
		                        	$("#maxpd").val(suminf.max); 
		                        	
		                            return '<div>总计:' + suminf.max + '</div>';
		                        },
		                        align: 'left'
		                    }
		                
		                },
		                
		                { display: '归集日期', name: 'imputDate', width: 150,format: 'yyyy-MM-dd', editor: { type: 'date'},render:renderDate }, 
		                { display: '还款日期', name: 'repayDate',format: 'yyyy-MM-dd', width: 150, editor: { type: 'date'},render:renderDate },
		                { display: '租金', name: 'rental',
		                    editor: { type: 'text' }, align: 'left', width: 180,totalSummary:
		                    {
		                        render: function (suminf, column, cell)
		                        {
		                        	//alert(suminf.count+":"+suminf.sum);
		                        	//$("#maxpd").val(suminf.max); 
		                        	
		                            return '<div>总计:' + suminf.sum.toFixed(2) + '</div>';
		                        },
		                        align: 'left'
		                    }
		                },
		                { display: '本金', name: 'capital',
		                    editor: { type: 'text' }, align: 'left', width: 180,totalSummary:
		                    {
		                        render: function (suminf, column, cell)
		                        {
		                        	//alert(suminf.count+":"+suminf.sum);
		                        	$("#paysum").val(suminf.sum); 
		                        	
		                            return '<div>总计:' + suminf.sum.toFixed(2) + '</div>';
		                        },
		                        align: 'left'
		                    }
		                },
		                { display: '利息', name: 'interest',
		                    editor: { type: 'text' }, align: 'left', width: 180
		                },
		                { display: '其他费用', name: 'otherChar',
		                    editor: { type: 'text' }, align: 'left', width: 150
		                },
		                { display: '超额抵押', name: 'overColl',
		                    editor: { type: 'text' }, align: 'left', width: 150
		                },
		                { display: '剩余本金', name: 'reCapital',
		                    editor: { type: 'text' }, align: 'left', width: 200
		                },	
		                { display: '预计退回时间', name: 'reReturnTm',format: 'yyyy-MM-dd', width: 150, editor: { type: 'date'},render:renderDate},
		                { display: '所属层级', name: 'plLv',
		                    editor: { type: 'text' }, align: 'left', width: 200
		                },
		                
		                 
	                ],
	                onSelectRow: function (rowdata, rowindex)
	                {
	                   // $("#txtrowindex").val(rowindex);
	                },
	                
	                onLoaded:function(){
	                	setTimeout(function () {  
	                		 while(parseInt($("#maxli").val())<parseInt($("#payplanli").val())){
	     	     	    		
	     	     	    		griddata1.addRow({});
	     	     	    		
	     	     	    	}
	       	        }, 2000);
	                	
	           		
	           		 this.toggleLoading(false);
	                },
	                usePager: false,
	                root: 'rows',
	                record: 'total',
	                hideLoadButton: true,
	                width: '100%',
	                height: 300,
	                heightDiff: -2,
	                enabledEdit: editFlag,
	                isScroll: false,
	                checkbox: editFlag,
	                rownumbers: true,
	                allowUnSelectRow: true,
	                alternatingRow: false,
	                enabledSort: false
	               
	            }); 
	    	
	    	
	    }
	  $("#scm_cost2_add_btn_id").click(function (event) {
		  griddata1.addRow({});
		  
		//  var mli=parseInt($("#maxli").val());
      //	var pli=parseInt($("#payplanli").val())
      //	var pd=parseInt($("#payplanpd").val())
      //	if(mli>pli){
	    	//	alert("true");
      		$("#payplanli").val($("#maxli").val());
	    //	}
      	
      	
	    });
	    
		$("#scm_cost2_del_btn_id").click(function (event) {
	        var selectedRows = griddata1.getSelectedRows();
	        if(selectedRows.length ==0){
				$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_ONLY_A_ROW, SQ_type: "warring"});
				return;
			}
			
			
	        griddata1.deleteSelectedRow();
	        setTimeout(function () {  
	        	 $("#payplanli").val($("#maxli").val());
	        }, 500);  
	       
	    });
		
		//格式化时间
		function renderDate(rowdata, index, value){
			var dateStr = "";
			if(null != value){
				var date = new Date(value);
				dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
			}
			return dateStr;
		}
		
		
		function f_initCostData0()
	    { 
			if(editFlag==''){
				editFlag=true;
			}
			var id=$("#prjid").val();
			var url='<%=path%>/rfbuss/fncprjbscinfo/initchgrList.do?id='+id;
	    	griddata0 = $("#cost0").ligerGrid({
	    		url:url,
	            method: 'get',
	                columns: [
	                	
		                { display: '行数', width: 80, name: 'lineNum',editor: { type: 'text' },
		                	render:function(item, rowindex){
		                		item.lineNum=rowindex+1;
		                		return item.lineNum;
		                	},
		                	 totalSummary:
			                    {
			                        render: function (suminf, column, cell)
			                        {	                        	
			                            return '<div>总共:' + suminf.count + '</div>';
			                        },
			                        align: 'left'
			                    }
		              
		                },		                
		                { display: '费用名称', name: 'costNm', width: 150, editor: { type: 'text'}}, 
		                { display: '还款日期', name: 'repayDate',format: 'yyyy-MM-dd', width: 100, editor: { type: 'date'},render:renderDate },
		                { display: '费用比例', name: 'costPct',
		                    editor: { type: 'text' }, width: 100,render:function (rowdata, rowindex, value, column) { 
			            		var h="";
			            		if(null!=value && value>0){
			            		     h=value*100/100;	
			            		}else{
			            			h="--"
			            		}
			            	return h;
			                
			            		},
		                },
		                { display: '费用金额', name: 'capital',
		                    editor: { type: 'text' }, align: 'left', width: 120,totalSummary:
		                    {
		                        render: function (suminf, column, cell)
		                        {
		                        	//alert(suminf.count+":"+suminf.sum);
		                        	$("#flsum").val(suminf.sum); 
		                        	
		                            return '<div>总共:' + suminf.sum + '</div>';
		                        },
		                        align: 'left'
		                    }
		                },
		                { display: '预计退回时间',name:'reReturnTm', format: 'yyyy-MM-dd', width: 100,editor: { type: 'date'},render:renderDate,align: 'left'}       
	                ],
	                onSelectRow: function (rowdata, rowindex)
	                {
	                   // $("#txtrowindex").val(rowindex);
	                },
	                
	             
	                onBeforeEdit: function(e){

	                    var colNanme = e.column.columnname;
	                    if (colNanme == "costNm" || colNanme == "lineNum" ||colNanme == "costPct") {
	    	            
                       	   e.column.editor.readonly = true;
                          }
	                         //e.column.editor.readonly = false;
	                         
	                    
	                    },
	                usePager: false,
	                root: 'rows',
	                record: 'total',
	                hideLoadButton: true,
	                width: '100%',
	                height: 300,
	                heightDiff: -2,
	                enabledEdit: editFlag,
	                isScroll: false,
	                checkbox: editFlag,
	                rownumbers: true,
	                allowUnSelectRow: true,
	                alternatingRow: false,
	                enabledSort: false
// 	                ,
// 	                isChecked: f_isChecked
	            }); 
	    	
	    	
	    }
		//默认选中
// 		function f_isChecked(rowdata)
// 		{
// 			return true;
// 		}
		//验证保证金的预计退回时间必填
		function getSelectRow() {
// 	        var rows = griddata0.getSelecteds();
	        var rows = griddata0.rows; 
	             for (var i = 0; i < rows.length; i++) {
	            	 var obj = $("#cost0").parent();
	                 if(rows[i].costNm == '保证金'&&(rows[i].reReturnTm =='undefined' || rows[i].reReturnTm == null || rows[i].reReturnTm == '')){
	                	// $(obj).css('border','1px #FF0000 solid');
// 	                	 alert("请维护融资端费用信息中保证金预计退回时间!");
	                	 $.ligerDialog.warn("融资端费用第"+(i+1)+"行[保证金退回时间]不能为空");
	                	 return false;
	                 }else{
	                	// $(obj).css('border','1px #F8F8F8 solid');
// 	                	 return true;
	                 }
	             }
	             return true; 
        }
		function getSelectRowcost1() {
	        var rows = griddata1.rows; 
             for (var i = 0; i < rows.length; i++) {
            	 if($.isNumeric(Number(rows[i].overColl))){
                	}else{
                		alert("还款表信息中第"+(i+1)+"期次的[超额抵押]只能输入数字!");
                		return false;
                	} 
//                  if(( rows[i].overColl != null &&  rows[i].overColl != "" && (rows[i].overColl != "0" ||rows[i].overColl != "0.00" || rows[i].overColl != "0.0"))&&(rows[i].reReturnTm =='undefined' || rows[i].reReturnTm == null || rows[i].reReturnTm == '')){
                 if(( rows[i].overColl != null &&  rows[i].overColl != "" && Number(rows[i].overColl) > 0)&&(rows[i].reReturnTm =='undefined' || rows[i].reReturnTm == null || rows[i].reReturnTm == '')){
                   				$.ligerDialog.warn("请维护还款表信息中第"+(i+1)+"期次的[预计退回时间]");
                     	 return false;
                }
             }
             return true; 
        }
		    
		 
		//启动流程
		function flowStart(){
			 
	            	//var wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting",onClose: function () {}});
	        		//var _id = $("#prjid").val();
	        		//$.ajax({
	            	//	type: 'post',
	            	//	dataType:'json',
	            	//	data:{
	            	//		id:_id,
	            	//		procDefKey:'FLOW_0000_R005_002',
	            	//		procDefId:'FLOW_0000_R005_002:5:4e9a8025-7cf1-11e7-87fb-005056b1519e',
	            	//		
	            	//		procNo:'再融资录入还款表审核'
	            	//	},
	            	//	url: '<%=path%>/rfbuss/fncprjbscinfo/addpayplanFlowStart.do',
	            	//	success:function(msg){
	            	//	
	            	//	}
	            	//});
	          
	        		 var modelTyp = "R005";
	        	        var flowDialog = $.ligerDialog.SQopen({
	        	            url: '<%=path%>/flow/flow/toForStartListPage.do?modelTyp='+modelTyp,
	        	            width: 700,
	        	            height:400,
	        	            title : '请选择要发起的流程',
	        	            buttons: [{
	        		                text: "确定", type: 'ok', cls: 'l-dialog-btn-ok',
	        		                onclick: function (item, Dialog) {
	        		                    if (Dialog.onOk) Dialog.onOk();
	        		                }
	        		            }, {
	        		                text: "取消", type: 'cancel', cls: 'l-dialog-btn-no',
	        		                onclick: function (item, Dialog) {
	        		                    if (Dialog.onCancel) Dialog.onCancel();
	        		                }
	        		            }
	        		        ],
	        	            onClose: function () {
	        	            
	        	            	var json = flowDialog._DATA;
	        	            
	        	            	//alert(json.procDefKey);
	        	            	//alert(json.procDefId);
	        	            	//alert(json.procNo);
	        	            	//console.log(json);
	        	            	if(!json){
	        	       
	        	                	return;
	        	            	}
	        	            
	        	            	var wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting",onClose: function () {}});
	        	            
	        	            	var _id = $("#prjid").val();
	        	        
	        	        		$.ajax({
	        	            		type: 'post',
	        	            		dataType:'json',
	        	            		data:{
	        	            			id:_id,
	        	            			procDefKey:json.procDefKey,
	        	            			procDefId:json.procDefId,
	        	            			procNo:json.procNo
	        	            		},
	        	            		url: '<%=path%>/rfbuss/fncprjbscinfo/addFlowStart.do',
	        	            		success:function(msg){
	        	            			
//	        	            			alert("msg.success="+msg.success);
	        	            			wait_dialog.close();
	        	            			 if(msg.success == 1){
	        	            				
	        	           					 UIUtils.alertSuccessHold1(msg.info);
	        	           					cancelBtn();
	        	            			 }else{
	        	           					 UIUtils.alertErrorHold1(msg.info);
	        	            			 }
	        	            		}
	        	            	});
	        	            }
	        	        });
	        		
		}
		function ReadExcel()
		{ 
			
			var _id = $("#prjid").val();
			var file=$("#upfile").val();
			
			//var ifxls=filename[filename.length-1];
			
			
			$.ajaxFileUpload({  
			    url : "<%=path%>/rfbuss/fncprjbscinfo/importExcel.do",  
			    dataType : 'json',  
			    data : {
                    id : _id
                },
			    secureuri : false,  
			    fileElementId :"upfile",  
			    success : function(msg) { //服务器成功响应处理函数  
			    	
			    	 if(msg.success == 1){
                            $("#payplanli").val(msg.data);
			    		 top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "success"});
        				// save();
       					// UIUtils.alertSuccessHold1(msg.info);
       					//ajaxFileUploadImg('upfile');
			    		 griddata1.reload();
        				
        				 
        			 }else{
        				 top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
       					// UIUtils.alertErrorHold1(msg.info);
        			 }  
			        }  
			    });  
			
		}
		
		function validateGrid() {  
            var rows = griddata0.rows;  
            for (var i = 0; i < rows.length; i++) { 
            	//alert(rows[i].costNm);
                if (rows[i].repayDate==null||rows[i].repayDate=="") {  
                    $.ligerDialog.warn("融资端费用第"+(i+1)+"行[还款日期]不能为空");  
                    return false;  
                }  
                if (rows[i].capital==null ||rows[i].capital=="") {  
                    $.ligerDialog.warn("融资端费用第"+(i+1)+"行[费用金额]不能为空");  
                    return false;  
                }  
                if (rows[i].capital<0) {  
                    $.ligerDialog.warn("融资端费用第"+(i+1)+"行[费用金额]不能为负数");  
                    return false;  
                }  
            }  
            var rows1 = griddata1.rows;  
            for (var i = 0; i < rows1.length; i++) { 
            	//alert(rows[i].costNm);
                if (rows1[i].repayDate==null||rows1[i].repayDate=="") {  
                    $.ligerDialog.warn("还款表第"+(i+1)+"行[还款日期]不能为空");  
                    return false;  
                }  
                if (rows1[i].imputDate==null || rows1[i].imputDate=="") {  
                    $.ligerDialog.warn("还款表第"+(i+1)+"行[归集日期]不能为空");  
                    return false;  
                } 
                if (rows1[i].pdMun==null || rows1[i].pdMun== "") {  
                    $.ligerDialog.warn("还款表第"+(i+1)+"行[期数]不能为空");  
                    return false;  
                }
                if (rows1[i].rental==null || rows1[i].rental=="") {  
                	if(Number(rows1[i].rental) == "0" ){}
                	else{
                    	$.ligerDialog.warn("还款表第"+(i+1)+"行[租金]不能为空");  
                    	return false; 
                    } 
                }
                if (rows1[i].capital==null || rows1[i].capital=="") { 
					if(Number(rows1[i].capital) == "0" ){}
					else{
	                    $.ligerDialog.warn("还款表第"+(i+1)+"行[本金]不能为空");  
	                    return false;  
					}
                }
                if (rows1[i].capital<0) {  
                    $.ligerDialog.warn("还款表第"+(i+1)+"行[本金]不能为负数");  
                    return false;  
                }
                if (rows1[i].interest==null||rows1[i].interest=="") {  
                	if(Number(rows1[i].interest) == "0"){}
                	else{
	                    $.ligerDialog.warn("还款表第"+(i+1)+"行[利息]不能为空");  
	                    return false;
                	}
                }
                if (rows1[i].interest<0) {  
                    $.ligerDialog.warn("还款表第"+(i+1)+"行[利息]不能为负数");  
                    return false;  
                }
                if (rows1[i].reCapital==null || rows1[i].reCapital=="") { 
                	if(Number(rows1[i].reCapital) == "0" ){}
                	else{
                    	$.ligerDialog.warn("还款表第"+(i+1)+"行[剩余本金]不能为空");  
                    	return false;  
                	}
                }
                if (rows1[i].reCapital<0) {  
                    $.ligerDialog.warn("还款表第"+(i+1)+"行[剩余本金]不能为负数");  
                    return false;  
                }
            }  
            
            if(rows1.length==0){
            	 $.ligerDialog.warn("请填写还款表");  
                 return false; 
            }
            return true;  
        }  
		
		function getRixx(){
			var ligerForm = liger.get("fnc_prj_bsc_info_form");
			 var data = ligerForm.getData();
		       data["prjid"]=$("#prjid").val();
		       if(data["orgCd"]==""){
		       data["orgCd"]='${orgCd}';
		       }
		       var payplanlist = griddata1.getData();
		       var fllist = griddata0.getData();
		       data["fstpyamt"]=new  Number("${fncPrjBscInfo.fstpyamtall/100}")
		       data["payplanlist"] = JSON.stringify(payplanlist);
		       data["fllist"] = JSON.stringify(fllist);
		       var transtm = "${fncPrjBscInfo.transtm}";
				//alert(transtm);
				if(null != transtm&&transtm!=''){
					var date = new Date(transtm);
				//	alert(date);
					  data["transtm"]=DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
				}
		      
		        var url = '<%=path%>/rfbuss/fncprjbscinfo/getXIRR.do';

		        var wait_dialog;
		        $.ajax({
		    		type: 'post',
		    		dataType:'json',
		    		data:data,
		    		url: url,
		    		beforeSend: function(){
				      //    wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
				     },
		    		success:function(msg){
		    			// wait_dialog.close();
		    			 if(msg.success == 1){
		    				
		    					// top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "success"});
					          	 	$("#acXirr").val(msg.data*100);
					          	 	pageInApp.flag=false;
		    			 }else{
		    				 top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
		    			 }
		    		}
		    	});
		}
		function getdura(){
			var ligerForm = liger.get("fnc_prj_bsc_info_form");
			 var data = ligerForm.getData();
		       data["prjid"]=$("#prjid").val();
		       if(data["orgCd"]==""){
		       data["orgCd"]='${orgCd}';
		       }
		       var payplanlist = griddata1.getData();
		       var fllist = griddata0.getData();
		       data["fstpyamt"]=new  Number("${fncPrjBscInfo.fstpyamtall/100}")
		       data["payplanlist"] = JSON.stringify(payplanlist);
		       data["fllist"] = JSON.stringify(fllist);
		       var transtm = "${fncPrjBscInfo.transtm}";
				//alert(transtm);
				if(null != transtm&&transtm!=''){
					var date = new Date(transtm);
				//	alert(date);
					  data["transtm"]=DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
				}
		      
		        var url = '<%=path%>/rfbuss/fncprjbscinfo/getDURA.do';

		        var wait_dialog;
		        $.ajax({
		    		type: 'post',
		    		dataType:'json',
		    		data:data,
		    		url: url,
		    		beforeSend: function(){
				      //    wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
				     },
		    		success:function(msg){
		    			// wait_dialog.close();
		    			 if(msg.success == 1){
		    				
		    					// top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "success"});
					          	 	$("#dura").val(msg.data);
					          	 	pageInApp.flag=false;
		    			 }else{
		    				 top.$.ligerDialog.SQalert({content: msg.info,SQ_type: "error"});
		    			 }
		    		}
		    	});
		}		
		//查看融资方案
		function showScmDetail(){
			var _id="${fncPrjBscInfo.fncscmid}";
			Add_navTab('PrdSpl_1'+_id,'查看融资方案','<%=path%>/rfbase/scmbaseinfo/toDetail.do?id='+_id);
		}
		
		//上传方法
		function ajaxFileUploadImg(){
			//var _filePath = $("#filePath").val();
			var _filePath = "REF";
			var fileId = "upfile";
			//文件上传
			$.ajaxFileUpload({  
				url:'<%=path%>/system/sysulfilesrec/upload.do',
				secureuri:false,  
				dataType: 'json',  
				fileElementId: fileId,  //上传框的id
				data: {filePath:_filePath},  
				success: function (msg){
					if(msg.success == 1){
						//累计上传文件-json数组-数组合并
						var upload_result_params = [];
						upload_result_params = upload_result_params.concat(msg.data);
						saveFile(JSON.stringify(msg.data));
					
	                } else{
	                    $.ligerDialog.SQalert({content:msg.info, SQ_type: "error"});
	                }
	            },
	            complete: function(){
	            	
	            }
			});  
		}
		
		//保存文件
		function saveFile(data){
	        var url = "<%=path%>/rfbuss/fncPrjContDetail/uploadAttchment.do";
	        var _id = $("#prjid").val();
        	if(null == data){
        		return false;
        	}else{
		        if(_id){
			        var param = {
						"docArray":data,
						"pkId": _id,
						"flag":'hkb'
					};
					//请求
			        AjaxUtils.ajaxPost(url, param, function(msg){
			        	if(msg.success == 1){
			        		//$("#cost1").ligerGrid('reload');
			        		loadFilesLiger('hkb',1, $("#prjid").val(),'no');//加载还款表附件信息
						 }else{
							 UIUtils.alertError(msg.info);
						 }
			        }, true);
		        }else{
		        	$.ligerDialog.SQalert({content: "业务主键为空-不能保存文件！",SQ_type: "error"});
		        }
        	}
		}
		
    </script>

</body>
</html>
